package com.zzh.lib.views.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.zzh.lib.views.adapter.holder.HSuperViewHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by ZZH on 2022/6/23.
 *
 * @Date: 2022/6/23
 * @Email: zzh_hz@126.com
 * @QQ: 1299234582
 * @Author: zzh
 * @Description: 基类
 */
public abstract class HBaseAdapter<T> extends BaseAdapter {
    protected List<T> mData;

    public HBaseAdapter() {
        mData = new ArrayList<>();
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public T getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    public void setNewInstance(List<T> data) {
        if (data != null) {
            mData = data;
        } else {
            mData.clear();
        }
        notifyDataSetChanged();
    }


    public void addAll(Collection<? extends T> data) {
        mData.addAll(data);
        notifyDataSetChanged();
    }

    public void add(T data) {
        mData.add(data);
        notifyDataSetChanged();
    }


    public void clear() {
        mData.clear();
        notifyDataSetChanged();
    }

    public void remove(T data) {
        mData.remove(data);
        notifyDataSetChanged();
    }

    public void remove(int index) {
        mData.remove(index);
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        HSuperViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(getLayoutRes(), parent, false);
            holder = new HSuperViewHolder(convertView);
            convertView.setTag(holder);

        } else {
            holder = (HSuperViewHolder) convertView.getTag();
        }
        onBindViewData(holder, getItem(position), position);
        return convertView;
    }

    protected abstract int getLayoutRes();

    protected abstract void onBindViewData(HSuperViewHolder holder, T item, int position);
}
